package com.bbshop.dao.product.impl;

import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Component;

import com.bbshop.bean.common.ProductTypeSearchCondition;
import com.bbshop.bean.common.SearchCondition;
import com.bbshop.bean.product.ProductType;
import com.bbshop.dao.base.DAOSupport;
import com.bbshop.dao.product.ProductTypeDAO;

@Component
public class ProductTypeDAOImpl extends DAOSupport<ProductType> implements
		ProductTypeDAO {
	@Override
	public void delete(Class<ProductType> entityClass, Object[] entityids) {
		StringBuffer jpq1 = new StringBuffer();
		if (entityids != null && entityids.length > 0) {
			for (int i = 0; i < entityids.length; i++) {
				jpq1.append("?").append(i + 2).append(",");

			}
			jpq1.deleteCharAt(jpq1.length() - 1);
		}

		Query query = em
				.createQuery("update ProductType o  set visible = ?1 where o.typeid in ("
						+ jpq1 + " )");
		query.setParameter(1, false);
		for (int i = 0; i < entityids.length; i++) {
			query.setParameter(i + 2, entityids[i]);
		}
		query.executeUpdate();
	}

	@Override
	public CriteriaQuery<ProductType> dealSearchCondition(CriteriaBuilder cb,
			SearchCondition<ProductType> sc) {
		CriteriaQuery<ProductType> cq=cb.createQuery(ProductType.class);
		Root<ProductType> root = cq.from(ProductType.class);
		ProductTypeSearchCondition ptsc = (ProductTypeSearchCondition) sc;
		Predicate p = null;
		if (ptsc.getParenttype() == null) {
			p = cb.isNull(root.get("parenttype"));
		}
		if (p == null)
			return cq;
		cq.where(p);
		return cq;
	}
}
